/**
 * Created by chenxiaoyu on 2018/6/6
 * Email 1524904743@qq.com
 */

define(['jquery'], function ($) {
    // 注册全局ajax拦截方法
    $(document).ajaxStart(function () {
        console.log("开始啦.....", this);
    })
    $(document).ajaxSend(function (event, request, settings) {
        console.log("发送啦.....", this);
    })
    $(document).ajaxComplete(function (event, request, settings) {
        console.log("结束啦.....", $(this));
    })
    var publicConfig= {
        home: 'fi fi-home',
        jquery: 'fi fi-jquery',
        angularjs: 'fi fi-angularjs',
        vuejs: 'fi fi-vuejs'
    };
    var obj= [{name:'首页',id:'code01',url: '../../index.html'},{name:'jQuery',id:'code02',url: '../../html/jquery/jqueryIndex.html'},
        {name:'angularJs',id:'code03',url: '../../html/angularjs/angularjsIndex.html'},{name:'Vuejs',id:'code04',url: '../../html/vuejs/vuejsIndex.html'}];
    // 获取url路径
    function getUrl() {
        var path= location.pathname;
        return path.substring(0, path.lastIndexOf('/'));
    };
    // 动态生成主导航
    function headerNav() {
        var module= getUrl();
        var nav= '<div class="public-nav-style text-aglin">';
        var classes= '';
        if (!!module){
            for (var i=0; i<obj.length; i++){
                if (obj[i].url.indexOf('/angularjs') != -1){
                    classes= publicConfig.angularjs;
                }else if (obj[i].url.indexOf('/vuejs') != -1){
                    classes= publicConfig.vuejs;
                }else if (obj[i].url.indexOf('/jquery') != -1){
                    classes= publicConfig.jquery;
                }else {
                    classes= publicConfig.home;
                }
                if (obj[i].url.indexOf(module) != -1){
                    classes+= ' color-white';
                    nav+= '<span id="'+obj[i].id+'" class="nav-active"><a href="'+obj[i].url+'"><i class="'+classes+'"> '+obj[i].name+'</i></a></span>';
                }else {
                    nav+= '<span id="'+obj[i].id+'"><a href="'+obj[i].url+'"><i class="'+classes+'"> '+obj[i].name+'</i></a></span>';
                }
            }
        }else {
            for (var i=0; i<obj.length; i++){
                if (obj[i].url.indexOf('/angularjs') != -1){
                    classes= publicConfig.angularjs;
                }else if (obj[i].url.indexOf('/vuejs') != -1){
                    classes= publicConfig.vuejs;
                }else if (obj[i].url.indexOf('/jquery') != -1){
                    classes= publicConfig.jquery;
                }else {
                    classes= publicConfig.home;
                }
                if (i === 0){
                    classes+= ' color-white';
                    nav+= '<span id="'+obj[i].id+'" class="nav-active"><a href="'+obj[i].url+'"><i class="'+classes+'"> '+obj[i].name+'</i></a></span>';
                }else {
                    nav+= '<span id="'+obj[i].id+'"><a href="'+obj[i].url+'"><i class="'+classes+'"> '+obj[i].name+'</i></a></span>';
                }
            }
        }
        nav+= '</div>';
        $('#publicHeader').append($(nav)).on('click', 'span', function ($this) {
            console.log($this)
        });
    };

    // 动态加载底部版权
    function footerLoad() {
        var divs= '<div class="footer-info"><p>友情链接：<a href="http://itwgy.com/" target="_blank">IT家园</a><a href="https://www.zhangxinxu.com/" target="_blank">张鑫旭博客</a>' +
            '<a href="http://edu.51cto.com/" target="_blank">51CTO学院</a><a href="http://www.runoob.com/" target="_blank">菜鸟学院</a><a href="http://www.daqianduan.com/nav" target="_blank">web前端工具导航</a>' +
            '<a href="http://www.alloyteam.com/nav/" target="_blank">web前端框架导航</a><a href="http://www.htmleaf.com/" target="_blank">jQuery之家</a></p><br/>' +
            '<p>Copyright © 2017 chen.com | QQ:1524904743 | 版权声明 | 陕ICP备12345678号-2 联系我们 | 网站地图 |</p></div>'
        $('body>div>footer').append($(divs));
    }
    // 动态加载左侧推荐列表
    function leftNavLoad() {
        $.ajax({
            method: 'get',
            url: '/data/left-nav.json',
            success: function (opt) {
                if (opt.code == 200){
                    var leftNav= '<div class="public-nav-title"><i class="fi fi-pinboard public-float-left"> </i>' +
                        '<span class="public-margin-left">本站推荐</span></div><div class="nav-left-list"><ul>';
                    for (var i=0; i<opt.data.length; i++){
                        var obj= opt.data[i];
                        leftNav+= '<li class="clearfix"><span class="public-float-left"><a href="'+obj.url+'">' +
                            '<img src="'+obj.imgUrl+'" alt=""/></a></span><span class="nav-left-item-title">' +
                            '<a href="'+obj.url+'">'+obj.title+'</a></span><span class="public-float-right">' +
                            '<i class="fi fi-eye color-blue"></i> <span class="color-gay">'+obj.counts+'</span></span></li>';
                    }
                    leftNav+= '</ul></div>';
                    $('.nav-left').html(leftNav);
                }
            }
        })
    };

    /**
     * 轮播封装
     * @type {number}   轮播方向，-1从右到左，1从左到右
     * @speed {number}  轮播速度，ms
     * @stop {number}   轮播间隔，ms
     */
    function InitCarousel(id) {
        this.id= id;    // 轮播图容器ID
        this.index= 0;  // 当前显示的图片下标
        this.activeFlag= true;  // 轮播状态控制变量
    }
    InitCarousel.prototype.init= function (type, speed, stop) {
        type= !type? -1: type;  // 轮播方向默认从右到左
        speed= !speed? 500: speed;  // 轮播速度默认500ms
        stop= !stop? 1000: stop;    // 轮播间隔默认1000ms
        var that= this;
        $('#'+that.id).addClass("carousel-box public-pos-re public-border-color");
        // 添加左右控制按钮
        var btns= '<div class="carousel-handle clearfix"><span class="public-float-left fi fi-angle-left"></span>' +
            '<span class="public-float-right fi fi-angle-right"></span></div>';
        $('#'+that.id).append($(btns));
        // 动态添加轮播数字按钮
        var handlePointer= '<div class="carousel-handle-round"><ol>';
        var activeImgs= $('#'+that.id+' ul li').length;
        for (var i=0; i<activeImgs; i++){
            handlePointer+= '<li>'+(i+1)+'</li>';
        }
        handlePointer+= '</div></ol>';
        $('#'+that.id).append($(handlePointer));

        // 首次启动轮播
        that.play(type, speed);
        // 轮播定时器
        var inter= setInterval(function () {
            that.play(type, speed);
        }, speed + stop);

        // 数字按钮绑定方法
        $('#'+that.id+' ol li').on('mouseenter', function (event) {
            var tagIndex= $(event.target).html() - 1;   // 目标图片的下标
            if (tagIndex != that.index){ // 当目标图片不是当前图片时
                if (that.activeFlag){    // 当可以轮播时
                    if (type == 1){
                        if (tagIndex < that.index){
                            that.play(type, speed, tagIndex);
                        }else {
                            that.play(-type, speed, tagIndex);
                        }
                    }else {
                        if (tagIndex < that.index){
                            that.play(-type, speed, tagIndex);
                        }else {
                            that.play(type, speed, tagIndex);
                        }
                    }
                }
            }
        })
        // 绑定鼠标进入或离开轮播区域时的事件
        $('#'+that.id).on({
            'mouseenter': function () {
                $('#'+that.id+' .carousel-handle').css('display', 'block');
                clearInterval(inter);
            },
            'mouseleave': function () {
                $('#'+that.id+' .carousel-handle').css('display', 'none');
                if (!!inter){
                    clearInterval(inter);
                }
                inter= setInterval(function () {
                    that.play(type, speed);
                }, speed + stop);
            }
        })
        // 绑定方向键的点击事件
        $('#'+that.id+' .carousel-handle').on('click', 'span', function () {
            var newType= $(this).hasClass('public-float-right')? -type: type;
            if (that.activeFlag){
                that.activeFlag= false;
                that.play(newType, speed);
            }
        });
    };
    // 轮播过程方法
    InitCarousel.prototype.play= function (direction, speed, tag) {
        var that= this;
        var liWidth= $('#'+that.id+' ul li').width();  // 获取每张图片的宽度，即每张图片滑动的距离
        that.activeFlag= false;
        var flag= direction == -1? true: false;
        var nextPic= that.index + 1;
        if ((tag == 0 || !!tag) && tag != that.index){
            nextPic= tag;
            $('.carousel-handle-round-active').removeClass('carousel-handle-round-active');
            $($('#'+that.id+' ol li')[nextPic]).addClass('carousel-handle-round-active');
        }else {
            $($('#'+that.id+' ol li')[that.index]).addClass('carousel-handle-round-active');
            if (!flag){
                nextPic= that.index - 1;
            }
        }
        // 下一张图片准备滑动进入
        if (flag){
            if (that.index >= $('#'+that.id+' ul li').length - 1) {
                nextPic= 0;
            }
            $('#'+that.id+' ul li')[nextPic].style.left= liWidth + 'px';
        }else {
            if (that.index <= 0){
                nextPic= $('#'+that.id+' ul li').length - 1;
            }
            $('#'+that.id+' ul li')[nextPic].style.left= -liWidth + 'px';
        }
        $('#'+that.id+' ul li')[nextPic].style.display= 'block';
        $('#'+that.id+' ul li')[nextPic].style.position= 'absolute';
        $('#'+that.id+' ul li')[nextPic].style.top= '0';
        // 开始动画
        $($('#'+that.id+' ul li')[that.index]).animate({    // 当前显示的图片开始离开
            left: direction * liWidth + 'px'
        }, speed, function () { // 当前图片离开后自动隐藏并初始化定位
            $(this).css('display', 'none').css('position', 'relative').css('left', 'initial').css('top', 'initial');
        });
        $($('#'+that.id+' ul li')[nextPic]).animate({  // 下一张图片开始进入
            left: 0 + 'px'
        }, speed, function () { // 下一张图片完全进入后
            that.activeFlag= true;
            $(this).css('position', 'relative');
            if ((tag == 0 || !!tag) && tag != that.index){
                that.index= tag;
            }else {
                if (flag){
                    that.index++;
                    if (that.index > $('#'+that.id+' ul li').length - 1) {
                        $('.carousel-handle-round-active').removeClass('carousel-handle-round-active');
                        that.index= 0;
                    }
                }else {
                    that.index--;
                    if (that.index < 0) {
                        that.index = $('#'+that.id+' ul li').length - 1;
                    }
                }
                $('.carousel-handle-round-active').removeClass('carousel-handle-round-active');
                $($('#'+that.id+' ol li')[that.index]).addClass('carousel-handle-round-active');
            }
        });
    }

    // 元素拖动
    function Drag(obj){
        this.disX= 0;
        this.disY= 0;
        this.obj= document.getElementById(obj);
        this.prts= [];
    }

    Drag.prototype.init= function(e){
        var that= this;
        that.obj.onmousedown= function(e){
            that.disX= e.pageX - that.obj.offsetLeft;
            that.disY= e.pageY - that.obj.offsetTop;
            that.getParents(that.obj);
            console.log(that.prts);
            document.onmousemove= function(e){
                var left= e.pageX - that.disX;
                var top= e.pageY - that.disY;
                var pare= '';
                for(var i in that.prts){
                    var pos= '';
                    if(that.prts[i].currentStyle){
                        pos= that.prts[i].currentStyle.position;
                    }else{
                        pos= window.getComputedStyle(that.prts[i]).position;
                    }
                    if(pos === 'relative'){
                        pare= that.prts[i];
                    }
                }
                if(!!pare){
                    var clientWidth= pare.offsetWidth - that.obj.offsetWidth - 2;
                    var clientHeight= pare.offsetHeight - that.obj.offsetHeight - 2;
                }else{
                    var clientWidth= (document.documentElement.clientWidth || document.body.clientWidth) - that.obj.offsetWidth;
                    var clientHeight= (document.documentElement.clientHeight || document.body.clientHeight) - that.obj.offsetHeight;
                }
                if(left < 0){
                    left= 0;
                }else if(left > clientWidth){
                    left= clientWidth;
                }

                if(top < 0){
                    top= 0;
                }else if(top > clientHeight){
                    top= clientHeight;
                }
                that.obj.style.left= left + 'px';
                that.obj.style.top= top + 'px';
            };
            document.onmouseup= function(){
                document.onmousemove= null;
                document.onmouseup= null;
                that.prts= [];
            };
        }
    }

    Drag.prototype.getParents= function(node){
        var prt= node.parentNode;
        if(prt.tagName !== 'body' && prt.tagName !== 'BODY'){
            this.prts.push(prt);
            this.getParents(prt);
        }
    }

    // 初始化内联富文本编辑器
    function InlineEditor(d, edit, type) {
        if (!d){
            throw '缺少必要参数d';
        }
        if (!edit){
            edit= require(['tinymce']);
        }
        var config= {
            selector: 'textarea',
            language: 'zh_CN',
            plugins: 'print preview fullpage searchreplace autolink directionality visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help',
            toolbar: 'formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat',
            image_advtab: true,
        }
        if (type==='inline'){
            config.inline= true;
            config.theme= 'inlite',
            config.insert_toolbar= 'quickimage quicktable underline',
            config.selector= d;
        }
        console.log(config)
        edit.init(config);
    }
    // 检测是否登录
    function isLogin() {
        var username= sessionStorage.getItem('username');
        if (!!username){
            $('.login-box-width>span:last-child').html('<a href="/html/persion/persionIndex.html" title="个人中心">' + username + '</a>');
        }
    }
    return {
        headerNav: headerNav,
        footerLoad: footerLoad,
        Drag: Drag,
        leftNavLoad: leftNavLoad,
        InitCarousel: InitCarousel,
        isLogin: isLogin,
        InlineEditor: InlineEditor
    }
})